package commons;

/**
 * This is main class being which is called when the user clicks on cos button
 */
public class CalculatorShruthi {
	public static final double pi = 3.14159265358979323846;

	/** Taylor series (1 - x^2/2! + x^4/4! - x^6/6) */
	public Double calculateCos(String str) {
		double input = Double.parseDouble(str);
		double reminder = input / 90;
		if (reminder % 2 != 0) {
			if (input % 90 == 0) {
				return 0.0;
			}
		}
		if (GUI.degButton.isSelected()) {
			input = convertToRadians(input);
		}
		double output = 1;
		int n = 2;
		long factorial = 1;
		double power = 1;
		while (n <= 21) {
			power *= calSquare(input, 2) * -1;
			factorial = calFactorial(n);
			output = output + (power / factorial);
			n = n + 2;
		}
		return output;
	}

	/** Convert degrees to radian */
	public double convertToRadians(double degree) {
		return degree / 180 * pi;
	}

	/** Calculate Factorial */
	private long calFactorial(int n) {
		if (n == 1 || n == 0) {
			return 1;
		} else {
			return n * calFactorial(n - 1);
		}
	}

	private Double calSquare(double x, int n) {
		for (int i = 1; i < n; i++) {
			x *= x;
		}
		return x;
	}
}
